#include <iostream>
#include <iomanip>
using namespace std;
#define BUFFER_SIZE 128

#include <sqlite3.h>
#include "stdDataBase.h"
#include "SQliteDataBase.h"

void demoExec(sqlite3 * musicDb)
{
    /* 将数据插入到数据库 */
    cout << " 请输入你的姓名" << endl;
    string name;
    cin >> name;
    
    cout << " 请输入你的密码" << endl;
    string passwd;
    cin >> passwd;

    const char * sql = "INSERT INTO userInfo(username, passwd) VALUES('%s', '%s');";
    char requestSql[BUFFER_SIZE] = { 0 };
    snprintf(requestSql, BUFFER_SIZE, sql, name.c_str(), passwd.c_str());
    
    /* 执行sql语句 */
    int ret = sqlite3_exec(musicDb, requestSql, NULL, NULL, NULL);
    if(ret != SQLITE_OK)
    {
        std::cout << " sqlite3 exec error" << endl;
        exit(-1);
    }
}

void testSelect(sqlite3 * musicDb)
{
    /* 查询数据 */
    const char * sql = "select * from userInfo;";
    char ** result = NULL;
    int row = 0;
    int column = 0;
    int ret = sqlite3_get_table(musicDb, sql, &result, &row, &column, NULL);
    if(ret != SQLITE_OK)
    {
        std::cout << " sqlite3 get table error" << endl;
        exit(-1);
    }


    for(int i = 1; i <= row; i++)
    {
        for(int j = 0; j < column; j++)
        {
            cout << result[i * column + j ] << "\t";
        }
        cout << endl;
    }

}
int main()
{

    const char * dbName = "./music.db";
    
    /* 数据库句柄 */
    sqlite3 * musicDb = NULL;   // 一定为NULL，不然可能会变成野指针

    /* 打开数据 */
    int ret = sqlite3_open(dbName, &musicDb);
    if(ret != SQLITE_OK)
    {
        std::cout << " sqlite3 error" << endl;
        exit(-1);
    }

    /* 插入数据 */
    //demoExec(musicDb);

    testSelect(musicDb);

    /* 关闭数据库 */
    sqlite3_close(musicDb);

    // const char * dbName = "./music.db";
    // StdDataBase * dataBase = new SQliteDataBase;
    // dataBase->connectDB(dbName);

    // const char * sql = "INSERT INTO userInfo(username, passwd) VALUES('123', '123');";
    
    // //dataBase->executeSql(sql);

    // const char * sql1 = "select * from userInfo;";
    // QueryResult res = dataBase->querySql(sql1);

    // for(int idx = 0; idx < res.columnName.size(); idx++)
    // {
    //     cout << res.columnName[idx] << setw(20);
    // }
    // cout << endl;

    // int rows = res.rows.size();
    // for(int idx = 0; idx < rows; idx++)
    // {
    //     /* 每一行的数据 */
    //     vector<string> rowData = res.rows[idx];

    //     for(int jdx = 0; jdx < rowData.size(); jdx++)
    //     {
    //         cout << rowData[jdx] << setw(20) ;
    //     }
    //     cout << endl;
    // }

    //dataBase->close();

    

    return 0;
}